package threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * @ClassName Wait
 * @Description TODO 展示wait和notify的基本方法
 *              1. 研究代碼執行順序
 *              2. 证明wait释放锁
 * @Author wushaopei
 * @Date 2021/4/19 22:36
 * @Version 1.0
 */
public class Wait {

    public static Object object = new Object();

    // 线程1进入wait状态，被线程2的notify唤醒
    static class Thread1 extends Thread{
        @Override
        public void run(){
            synchronized (object){
                System.out.println("线程" + Thread.currentThread().getName() + "开始执行了");
                try {
                    object.wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + "获取到了锁");
            }
        }
    }
    // 唤醒线程1的wait
    static class Thread2 extends Thread{
        @Override
        public void run() {
            synchronized (object){
                object.notify();
                System.out.println("线程" + Thread.currentThread().getName() + "调用了notify()");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.start();
        Thread.sleep(200);
        thread2.start();

    }
}
